package pers.cz.mock;

import pers.cz.context.MyThreadLocals;
import pers.cz.util.CollectType;
import pers.cz.util.ColletExecutor;
import pers.cz.util.RedisConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 接口mock
 * @program: postgirl-collection-client
 * @description: InterfaceMock
 * @author: Cheng Zhi
 * @create: 2022-02-07 19:22
 **/
public class InterfaceMock {

    private static RedisConfig redisUtil = null;

    static {
        redisUtil = new RedisConfig();
    }

    public static void begin(Integer busiCode, String soMode) {

        // 作为后续的traceId,这里使用接口编号+当前时间戳+随机数的组合
        MyThreadLocals.context.set(busiCode + "||" + System.currentTimeMillis() + (int)((Math.random()*9+1)*10000000));

        // 如果soMode为指定渠道,表示该请求来源于postgirl
        if (soMode.equals("999")) {
            MyThreadLocals.methodContext.set(soMode);
        }
    }
    public static void middle(String arg0, String arg1, Integer arg2) {

        try {
            // 只有不是postgirl发起的请求才录制
            if (MyThreadLocals.methodContext.get() == null) {
                final String request = arg0;
                final String response = arg1;
                final Integer busiCode = arg2;
                String traceId = MyThreadLocals.context.get();
                ColletExecutor executor = ColletExecutor.getInstance(CollectType.INTERFACE_COLLECT);
                JedisPool jedisPool = redisUtil.redisPoolFactory();
                Jedis resource = jedisPool.getResource();
                executor.executeTask(new InterfaceThread(request, response, busiCode, resource, traceId));
                MyThreadLocals.context.remove(); // 清空上下文
                MyThreadLocals.methodContext.remove(); // 清空上下文
            }
        } catch (Exception e) {
            System.out.println("postgirl-collection-client error :" + e.getMessage());
        }
    }


}
